package pers.yefeng.utils;

import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author WangHongHui
 * @date 2021/11/16 10:26:38
 */
@Slf4j
public class NetUtil {

    /**
     * 检测ip和端口是否可连接
     */
    public static boolean isHostConnectable(String host, int port) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(host, port), 3 * 1000);
        } catch (IOException e) {
            log.error("ip和端口不可连接：{}:{},{}", host, port, ExceptionUtil.getMessage(e));
            return false;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    /**
     * 检测ip是否可连接
     */
    public static boolean isHostReachable(String host, Integer timeOut) {
        try {
            return InetAddress.getByName(host).isReachable(timeOut);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
